<?php
namespace plugin\ky_shouyin\app\service;

use support\Db;

class PointsService
{
    /**
     * 计算订单可获得的积分
     */
    public function calculateOrderPoints($amount)
    {
        // 获取启用的消费赠送规则
        $rules = Db::table('ky_points_rule')
            ->where('type', 1)
            ->where('status', 1)
            ->orderBy('condition', 'desc')
            ->get();
            
        $points = 0;
        foreach ($rules as $rule) {
            if ($amount >= $rule->condition) {
                $points = floor($amount / $rule->condition) * $rule->points;
                break;
            }
        }
        
        return $points;
    }
    
    /**
     * 赠送积分
     */
    public function addPoints($memberId, $points, $type, $orderId = null, $description = '')
    {
        try {
            Db::beginTransaction();
            
            // 添加积分记录
            Db::table('ky_points_log')->insert([
                'member_id' => $memberId,
                'points' => $points,
                'type' => $type,
                'order_id' => $orderId,
                'description' => $description,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            // 更新会员积分
            Db::table('ky_member')
                ->where('id', $memberId)
                ->increment('points', $points);
            
            // 检查是否需要升级
            $this->checkMemberUpgrade($memberId);
            
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollBack();
            return false;
        }
    }
    
    /**
     * 使用积分
     */
    public function usePoints($memberId, $points, $orderId, $description = '')
    {
        try {
            Db::beginTransaction();
            
            // 检查积分是否足够
            $member = Db::table('ky_member')
                ->where('id', $memberId)
                ->first();
                
            if ($member->points < $points) {
                throw new \Exception('积分不足');
            }
            
            // 添加积分记录
            Db::table('ky_points_log')->insert([
                'member_id' => $memberId,
                'points' => -$points,
                'type' => 3,
                'order_id' => $orderId,
                'description' => $description,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            // 更新会员积分
            Db::table('ky_member')
                ->where('id', $memberId)
                ->decrement('points', $points);
            
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollBack();
            return false;
        }
    }
    
    /**
     * 检查会员升级
     */
    protected function checkMemberUpgrade($memberId)
    {
        // 获取会员信息
        $member = Db::table('ky_member')
            ->where('id', $memberId)
            ->first();
            
        // 获取所有等级
        $levels = Db::table('ky_member_level')
            ->orderBy('upgrade_points', 'desc')
            ->get();
            
        // 检查是否需要升级
        foreach ($levels as $level) {
            if ($member->points >= $level->upgrade_points && $member->level < $level->id) {
                Db::table('ky_member')
                    ->where('id', $memberId)
                    ->update([
                        'level' => $level->id,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                break;
            }
        }
    }
    
    /**
     * 获取积分记录
     */
    public function getPointsLog($memberId, $page = 1, $limit = 15)
    {
        $query = Db::table('ky_points_log')
            ->where('member_id', $memberId)
            ->orderBy('id', 'desc');
            
        $total = $query->count();
        $logs = $query->offset(($page - 1) * $limit)
                     ->limit($limit)
                     ->get();
                     
        return [
            'total' => $total,
            'data' => $logs
        ];
    }
} 